package utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Matrix;
import android.media.ExifInterface;

import com.shishi.tech.paipai.application.BaseApplication;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import utils.common.ScreenTools;


@SuppressLint("NewApi")
public class BitmapHelper {

    /**
     * get the orientation of the bitmap {@link ExifInterface}
     * @param path
     * @return
     */
    public final static int getDegress(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * rotate the bitmap
     *
     * @param bitmap
     * @param degress
     * @return
     */
    public static Bitmap rotateBitmap(Bitmap bitmap, int degress) {
        if (bitmap != null) {
            Matrix m = new Matrix();
            m.postRotate(degress);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);
            return bitmap;
        }
        return bitmap;
    }


    /**
     * @param options
     * @param rqsW
     * @param rqsH
     * @return
     */
    public final static int caculateInSampleSize(Options options, int rqsW, int rqsH) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > rqsH || width > rqsW) {
            final int heightRatio = Math.round((float) height / (float) rqsH);
            final int widthRatio = Math.round((float) width / (float) rqsW);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    /**
     * @param path bitmap source path
     * @param rqsW
     * @param rqsH
     * @return Bitmap {@link Bitmap}
     */
    public final static Bitmap compressBitmap(String path, int rqsW, int rqsH) {
        final Options options = new Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        options.inSampleSize = caculateInSampleSize(options, rqsW, rqsH);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(path, options);
    }

    /**
     * 压缩图片，等比例压缩手机宽高，大小不超过200KB
     *
     * @param context
     * @param path
     * @return
     */
    public static Bitmap compressBitmap(Context context, String path) {
        Bitmap bitmap = compressBitmap(path, ScreenTools.getInstance(context).getScreenWidth(), ScreenTools.getInstance(context).getScreenHeight());
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里10表示不压缩，把压缩后的数据存放到baos中
            byte[] b = baos.toByteArray();
            //将字节换成KB
            double mid = b.length / 1024;
            //图片允许最大空间 单位：KB
            double maxSize = 200.00;
            if (mid > maxSize) {
                int options = 100;
                while (mid > maxSize && options / 3 > 0) { // 循环判断如果压缩后图片是否大于10kb,大于继续压缩
                    baos.reset();// 重置baos即清空baos
                    options -= options / 3;// 每次都减少30%
                    bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
                    mid = baos.toByteArray().length / 1024;
                }
                ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
                return BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
            }
        } catch (Exception e) {
        }
        return bitmap;
    }


    /**
     * 压缩图片，等比例压缩手机宽高，大小不超过200KB,如果图片本身大小不超过200KB 就不压缩
     *
     * @param context
     * @param bitmap
     * @return
     */
    public static Bitmap compressBitmap(Context context, Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里10表示不压缩，把压缩后的数据存放到baos中
        byte[] b = baos.toByteArray();
        //将字节换成KB
        double mid = b.length / 1024;
        //图片允许最大空间 单位：KB
        double maxSize = 200.00;
        if (mid > maxSize) {
            Bitmap imgBitmap = compressBitmap(b, ScreenTools.getInstance(context).getScreenWidth(), ScreenTools.getInstance(context).getScreenHeight());
            imgBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里10表示不压缩，把压缩后的数据存放到baos中
            byte[] tb = baos.toByteArray();
            //将字节换成KB
            double midk = tb.length / 1024;
            if (midk > maxSize) {
                int options = 100;
                while (mid > maxSize && options / 3 > 0) { // 循环判断如果压缩后图片是否大于10kb,大于继续压缩
                    baos.reset();// 重置baos即清空baos
                    options -= options / 3;// 每次都减少20%
                    imgBitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
                    mid = baos.toByteArray().length / 1024;
                }
                ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
                return BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
            }
            return imgBitmap;
        }
        return bitmap;
    }


    /**
     * @param bts
     * @param reqsW
     * @param reqsH
     * @return
     */
    public final static Bitmap compressBitmap(byte[] bts, int reqsW, int reqsH) {
        final Options options = new Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(bts, 0, bts.length, options);
        options.inSampleSize = caculateInSampleSize(options, reqsW, reqsH);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeByteArray(bts, 0, bts.length, options);
    }


    private Bitmap revitionImageSize(String path, int size) throws IOException {
        // 取得图片
        InputStream temp = BaseApplication.getInstance().getAssets().open(path);
        Options options = new Options();
        // 这个参数代表，不为bitmap分配内存空间，只记录一些该图片的信息（例如图片大小），说白了就是为了内存优化
        options.inJustDecodeBounds = true;
        // 通过创建图片的方式，取得options的内容（这里就是利用了java的地址传递来赋值）
        BitmapFactory.decodeStream(temp, null, options);
        // 关闭流
        temp.close();
        // 生成压缩的图片
        int i = 0;
        Bitmap bitmap = null;
        while (true) {
            // 这一步是根据要设置的大小，使宽和高都能满足
            if ((options.outWidth >> i <= size)
                    && (options.outHeight >> i <= size)) {
                // 重新取得流，注意：这里一定要再次加载，不能二次使用之前的流！
                temp = BaseApplication.getInstance().getAssets().open(path);
                // 这个参数表示 新生成的图片为原始图片的几分之一。
                options.inSampleSize = (int) Math.pow(2.0D, i);
                // 这里之前设置为了true，所以要改为false，否则就创建不出图片
                options.inJustDecodeBounds = false;
                bitmap = BitmapFactory.decodeStream(temp, null, options);
                break;
            }
            i += 1;
        }
        return bitmap;
    }


}